<script setup lang="ts">
import { computed, h, onMounted, ref, watchEffect } from 'vue'
import { getSpaceByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { formatSize } from '@/utils'
import PicList from '@/components/PicList.vue'
import { searchPicByColorUsingPost, userPicPageUsingPost } from '@/api/fileController.ts'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditModal from '@/components/BatchEditModal.vue'
import { EditOutlined, FullscreenExitOutlined } from '@ant-design/icons-vue'
import { SPACE_PERMISSION_ENUM } from '@/constants/spaceUser.ts'
import { useRoute } from 'vue-router'

// 转圈
const loading = ref(true)
// 分页查询结果
const pictureList = ref<API.PictureVO[]>([])
// 定义总条数
const total = ref(0)
//弹窗引用
const batchEditModalRef = ref()
const route = useRoute()

// 定义查询参数,默认1页10条
const queryParams = ref<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'editTime',
  sortOrder: 'descend',
})

const spaceId = computed(() => {
  return route.query?.spaceId
})

const space = ref<API.Space>()

function checkPremission(premission: string) {
  return computed(() => {
    return (space.value?.premissionList ?? []).includes(premission)
  })
}

// 定义权限检查
const canManageSpaceUser = checkPremission(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canViewPicture = checkPremission(SPACE_PERMISSION_ENUM.PICTURE_VIEW)
const canUploadPicture = checkPremission(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = checkPremission(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = checkPremission(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

// 定义分页对象
const onChange = (current: number, pageSize: number) => {
  queryParams.value.current = current
  queryParams.value.pageSize = pageSize
  getPageData()
}

// 从后端分页查询数据，注意这里要传自己的空间ID
async function getPageData() {
  loading.value = true
  const params = {
    spaceId: spaceId.value,
    ...queryParams.value,
  }

  const resp = await userPicPageUsingPost(params)
  if (resp.data.code === 0 && resp.data.data) {
    pictureList.value = resp.data.data.records ?? []
    total.value = resp.data.data.total ?? 0

    console.log(pictureList.value)
  } else if (resp.data.data === null) {
    message.error('查询无记录')
  } else {
    message.error('查询图片数据失败,' + resp.data.message)
  }

  loading.value = false
}

// 根据ID获取空间详情
async function querySpaceDetailById() {
  const resp = await getSpaceByIdUsingGet({
    id: spaceId.value,
  })
  if (resp.data.code === 0 && resp.data.data) {
    space.value = resp.data.data
  } else {
    message.error(resp.data.message)
  }
}

/**
 * 接收子组件的传值，进行搜索
 */
async function doSearch(newSearchParams: API.PictureQueryRequest) {
  queryParams.value = {
    ...queryParams.value,
    ...newSearchParams,
  }
  getPageData()
}

/**
 * 按照颜色搜索
 * @param color
 */
async function onColorChange(color: string) {
  const resp = await searchPicByColorUsingPost({
    picColor: color,
    spaceId: spaceId.value,
  })
  if (resp.data.code === 0 && resp.data.data) {
    const data = resp.data.data ?? []
    pictureList.value = data
    total.value = data.length
  } else {
    message.error(resp.data.message)
  }
}

/**
 * 打开批量编辑组件
 */
// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditModalRef.value) {
    batchEditModalRef.value.handleOpen()
  }
}

watchEffect(() => {
  querySpaceDetailById()
  getPageData()
})
</script>

<template>
  <div id="spaceDetail">
    <!--      空间详情-->
    <a-flex justify="space-between">
      <h3>
        {{
          space?.spaceType == 0 ? space?.spaceName + '的私有空间' : space?.spaceName + '的团队空间'
        }}
      </h3>
      <a-space size="middle">
        <!--        跳转到成员管理页面-->
        <a-button
          type="primary"
          :href="`/space/spaceUserManage?spaceId=${space?.id}`"
          v-if="space?.spaceType === 1 && canManageSpaceUser"
        >+ 成员管理
        </a-button>
        <!--        跳转到添加图片页面-->
        <a-button
          type="primary"
          :href="`/picture/addPicture?spaceId=${space?.id}`"
          target="_blank"
          v-if="canUploadPicture"
        >+ 创建图片
        </a-button>
        <!--        批量编辑-->
        <a-button type="primary" :icon="h(EditOutlined)" @click="doBatchEdit" v-if="canEditPicture">
          + 批量编辑
        </a-button>
        <!--        点击按钮跳转到图库分析页面,带上空间ID-->
        <a-button
          type="primary"
          :icon="h(FullscreenExitOutlined)"
          :href="`/analyze/picture?spaceId=${space?.id}`"
          v-if="canViewPicture"
        >
          图库分析
        </a-button>
        <a-tooltip
          :title="`占用空间 ${formatSize(space?.totalSize)} / ${formatSize(space?.maxSize)}`"
        >
          <a-progress
            type="circle"
            :percent="((space?.totalSize * 100) / space?.maxSize).toFixed(1)"
            :size="42"
          />
        </a-tooltip>
      </a-space>
    </a-flex>
    <!--    引入图片搜索组件-->
    <PictureSearchForm :onsearch="doSearch" />
    <!--    颜色搜图-->
    <div style="margin-bottom: 16px">
      按照颜色搜索
      <!-- 按颜色搜索 -->
      <color-picker format="hex" @pureColorChange="onColorChange" style="margin-left: 8px" />
    </div>
    <!--    引用图片子组件,向子组件传值-->
    <PicList
      :picture-list="pictureList"
      :loading="loading"
      :privateShow="true"
      :on-reload="getPageData"
      :canEdit="canEditPicture"
      :canDel="canDeletePicture"
    />
    <!--    分页-->
    <a-pagination
      style="text-align: right"
      v-model:current="queryParams.current"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :show-total="() => `图片总数${total} / ${space?.maxCount}`"
      @change="onChange"
    ></a-pagination>
    <BatchEditModal
      ref="batchEditModalRef"
      :pictureList="pictureList"
      :spaceId="spaceId"
      :onSuccess="getPageData"
    ></BatchEditModal>
  </div>
</template>

<style scoped></style>
